package com.wbc.smartHome.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.wbc.smartHome.dao.UserDao;
import com.wbc.smartHome.model.Result;
import com.wbc.smartHome.model.User;
import com.wbc.smartHome.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    /*验证邮箱的正则表达式*/
    private static final String EMAIL_REGEX = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";

    // 验证邮箱格式的方法
    private boolean isValidEmail(String email) {
        // 创建 Pattern 对象
        Pattern pattern = Pattern.compile(EMAIL_REGEX);
        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(email);

        // 查看 email 是否符合正则表达式
        return matcher.matches();
    }


    public Result createYzm(String account) {

        // 验证邮箱格式
        if (!isValidEmail(account)) {
            return new Result(400, "邮箱格式不正确，请输入有效的邮箱地址", 0);
        }
        //向邮箱发送验证码
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1790352490@qq.com");//发送的qq邮箱
        message.setTo(account);//接收邮件的QQ邮箱
        message.setSubject("主题：注册验证码");
            //随机生成六位数字
            Random random = new Random();
            int randomNum = random.nextInt(1000000);
            String randomCode = String.format("%06d", randomNum);
        message.setText("验证码："+randomCode);//设置发送的内容
        mailSender.send(message);

        //将验证码存入redis
        ValueOperations valueOperations =redisTemplate.opsForValue();
        valueOperations.set(account,randomCode,5,TimeUnit.MINUTES);
        return new Result(200,"验证码发送成功",2);
    }

    public Result regUser(User user) {
        //1、判断是否存在、
        if (!redisTemplate.hasKey(user.getAccount())) {
            return new Result(200,"验证码不存在",1);
        }
        //2、验证验证码是否正确
        String yzm = (String) redisTemplate.opsForValue().get(user.getAccount());
        if (!yzm.equals(user.getYzm())) {
            return new Result(200,"验证码不正确",2);
        }
        //生成昵称
        user.setName("用户"+user.getAccount().substring(0,7));
        //生成状态
        user.setState(1);
        //4、存入mysql
        userDao.saveUser(user);
        redisTemplate.delete(user.getAccount());
        return new Result(200,"注册成功",3);
    }

    public Result loginUser(User user) {
        int count = userDao.checkAccount(user.getAccount());
        if (count == 0) {
            Result result = regUser(user);
            if (result.getData().equals(1)||result.getData().equals(2)){
                return result;
            }
        }
        else if (count == 1) {
            String yzm1 = user.getYzm();
            ValueOperations valueOperations =redisTemplate.opsForValue();
            String yzm2 = (String) valueOperations.get(user.getAccount());
            if (!yzm1.equals(yzm2)) {
                return new Result(200, "验证码错误，请重试", 4);
            }
            else {
                redisTemplate.delete(user.getAccount());
            }
        }
        User user1 = userDao.loginUser(user);
        if (user1 != null) {
            if (user1.getState()==2) {
                return new Result(200,"账号已被封禁，请联系管理员",3);
            }
            user1.setUserToken(JWTUtil.getToken(user));
            return new Result(200,"登陆成功0.0",user1);
        }
        else return new Result(200,"系统发生错误请稍后重试",2);
    }

    public Result uploadImg(CommonsMultipartFile commonsMultipartFile) throws IOException {
        //为了避免上传的文件重名,重新生成一个文件名
        String newFileName = new Date().getTime()+commonsMultipartFile.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+endpoint, accessKeyId, accessKeySecret);
        //长传文件
        ossClient.putObject(bucketName, newFileName, commonsMultipartFile.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newFileName;
        //newsDao.savePhoto(url);
        return new Result(200,"操作成功",url);
    }

    public User update(User user, String userToken) {

        boolean flag = JWTUtil.verify(userToken);
        if (!flag) {
            return null;
        }
        userDao.updateUser(user);
        User user1 = userDao.updateReturn(user);
        return user1;
    }



}
